package com.linjj.seckill.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linjj.seckill.access.AccessLimit;
import com.linjj.seckill.domain.User;
import com.linjj.seckill.service.IGoodsService;
import com.linjj.seckill.vo.Result;
import com.linjj.seckill.vo.SeckillGoodsDetailVo;
import com.linjj.seckill.vo.SeckillGoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
 * 商品控制器
 * */
@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private IGoodsService goodsService;

    /**
     * 秒杀列表
     * */
    @AccessLimit(seconds=5,maxCount=5,needLogin=false)
    @GetMapping("/seckill/list")
    @ResponseBody
    public Result list(int page){
        PageHelper.startPage(page,5);
        List<SeckillGoodsVo> goodsList = goodsService.seckillList();
        return Result.success(new PageInfo<>(goodsList));
    }
    /**
     * 未开始
     * */
    @AccessLimit(seconds=5,maxCount=5,needLogin=false)
    @GetMapping("/seckill/notstart")
    @ResponseBody
    public Result notStartList(int page){
        PageHelper.startPage(page,5);
        List<SeckillGoodsVo> notStartList = goodsService.notStartList();
        return Result.success(new PageInfo<>(notStartList));
    }
    /**
     * 进行中
     * */
    @AccessLimit(seconds=5,maxCount=5,needLogin=false)
    @GetMapping("/seckill/started")
    @ResponseBody
    public Result startedList(int page){
        PageHelper.startPage(page,5);
        List<SeckillGoodsVo> startedList = goodsService.startedList();
        return Result.success(new PageInfo<>(startedList));
    }
    /**
     * 已结束
     * */
    @AccessLimit(seconds=5,maxCount=5,needLogin=false)
    @GetMapping("/seckill/over")
    @ResponseBody
    public Result overList(int page){
        PageHelper.startPage(page,5);
        List<SeckillGoodsVo> overList = goodsService.overList();
        return Result.success(new PageInfo<>(overList));
    }


    /**
     * 秒杀商品详情
     * */
    @AccessLimit(seconds=5,maxCount=5,needLogin=true)
    @GetMapping("/seckill/detail/{goodsId}")
    @ResponseBody
    public Result seckillDetail(User user,@PathVariable("goodsId")long goodsId) {
        SeckillGoodsVo seckillVo = goodsService.getSeckillVoByGoodsId(goodsId);
        long startAt = seckillVo.getSeckillStart().getTime();
        long endAt = seckillVo.getSeckillEnd().getTime();
        long now = System.currentTimeMillis();
        int remainSeconds = 0;
        if(now < startAt ) {//秒杀还没开始，倒计时
            remainSeconds = (int)((startAt - now )/1000);
        }else  if(now > endAt){//秒杀已经结束
            remainSeconds = -1;
        }else {//秒杀进行中
            remainSeconds = 0;
        }
        SeckillGoodsDetailVo detail = new SeckillGoodsDetailVo(seckillVo,user,remainSeconds);
        return Result.success(detail);
    }

}
